package cs2340.droidceptiontodo;

//Imports, you must have google API's installed to have this work
//you can manually add the google api's library by right clicking on the project, 
//clicking properties --> android--> and changing the build target to Google APIs
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONArray;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.ItemizedOverlay;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.location.Address;
import android.location.Geocoder;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
 
import com.google.android.maps.OverlayItem; 


//must extend a MapActivity, not an Activity
public class MapsActivity extends MapActivity 
{    
    private MapView mapView;
    private MapController mapControl;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.mapview);
        
        mapView = (MapView) findViewById(R.id.mapView);
        Geocoder geo = new Geocoder(this, Locale.getDefault());
        GeoPoint p = getGeoPoint(getLocationInfo("Atlanta+Georgia"));
        
        List<Overlay> mapOverlays = mapView.getOverlays();
        Drawable drawable = this.getResources().getDrawable(R.drawable.pushpinclipart5);
        drawable.setBounds(0,0,drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
        HelloItemizedOverlay itemizedOverlay = new HelloItemizedOverlay(drawable, this);
        
        //Database locGetter = new Database(this);
        Database locGetter = Database.getInstance(this);
        locGetter.open();
        ArrayList<ToDoItem> items = locGetter.getItems(locGetter.getUser().getID());
        ArrayList<String> locStrings = new ArrayList<String>();
        ArrayList<GeoPoint> locs = new ArrayList<GeoPoint>();
        for(ToDoItem i: items){
        	if(i.getLocation() != null || i.getLocation()!= ""){
        		String loc = stringRep(i.getLocation());
        		locStrings.add(loc);
        	}
        }
        try{
        	for(String s: locStrings){
        		locs.add(getGeoPoint(getLocationInfo(s)));
        	}
        	Log.d("Debug", "I hope this works");
        	int counter = 0;
        	for(GeoPoint g: locs){
        		itemizedOverlay.addItem(g, "point"+ counter, "point"+counter);
        		counter++;
        	}
        	mapView.getOverlays().add(itemizedOverlay);
        	mapView.postInvalidate();
        }
        catch(Exception e){
        	Log.d("Debug", e.toString());
        }
       /**
		ArrayList<GeoPoint> points = new ArrayList<GeoPoint>();
		
		GeoPoint myPoint1 = new GeoPoint((int)(33.706063*1000000),(int)(-84.342041*1000000));
		itemizedoverlay.addItem(myPoint1, "myPoint1", "myPoint1");
		GeoPoint myPoint2 = new GeoPoint((int)(33.779179*1000000), (int)(-84.399630*1000000));
		itemizedoverlay.addItem(myPoint2, "myPoint2", "myPoint2"); 
		mapView.getOverlays().add(itemizedoverlay);
		    
		mapView.postInvalidate(); 
        **/
       
        mapControl = mapView.getController();
        mapControl.animateTo(p);
        //mapView.setSatellite(true);
        //mapView.setStreetView(true);
        mapView.invalidate();
        
        
        /**
         * Geocoder geoCoder = new Geocoder(this, Locale.getDefault());    
                try {
                    List<Address> addresses = geoCoder.getFromLocationName(
                        "empire state building", 5);
                    String add = "";
                    if (addresses.size() > 0) {
                        p = new GeoPoint(
                                (int) (addresses.get(0).getLatitude() * 1E6), 
                                (int) (addresses.get(0).getLongitude() * 1E6));
                        mc.animateTo(p);    
                        mapView.invalidate();
                    }    
                } catch (IOException e) {
                    e.printStackTrace();
                }
         * @author Sheena
         *
         */
    }
	public boolean onKeyDown(int keyCode, KeyEvent event){
		switch(keyCode){
			case KeyEvent.KEYCODE_4:
			mapControl.zoomIn();
			break;
			case KeyEvent.KEYCODE_2:
			mapControl.zoomOut();
			break;
			
		}
		return super.onKeyDown(keyCode, event);
	}
 
    @Override
    protected boolean isRouteDisplayed() {
        return false;
    }
	public static String stringRep(String address){
		return address.replaceAll("[\\s,]", "\\+");
	}
    public static JSONObject getLocationInfo(String address) {

		HttpGet httpGet = new HttpGet("http://maps.google.com/maps/api/geocode/json?address=" + address
				+ "ka&sensor=false");
		HttpClient client = new DefaultHttpClient();
		HttpResponse response;
		StringBuilder stringBuilder = new StringBuilder();

		try {
			response = client.execute(httpGet);
			HttpEntity entity = response.getEntity();
			InputStream stream = entity.getContent();
			int b;
			while ((b = stream.read()) != -1) {
				stringBuilder.append((char) b);
			}
		} catch (ClientProtocolException e) {
		} catch (IOException e) {
		}

		JSONObject jsonObject = new JSONObject();
		try {
			jsonObject = new JSONObject(stringBuilder.toString());
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return jsonObject;
	}

public static GeoPoint getGeoPoint(JSONObject jsonObject) {

		Double lon = new Double(0);
		Double lat = new Double(0);

		try {

			lon = ((JSONArray)jsonObject.get("results")).getJSONObject(0)
				.getJSONObject("geometry").getJSONObject("location")
				.getDouble("lng");

			lat = ((JSONArray)jsonObject.get("results")).getJSONObject(0)
				.getJSONObject("geometry").getJSONObject("location")
				.getDouble("lat");

		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return new GeoPoint((int) (lat * 1E6), (int) (lon * 1E6));

	}
	private class HelloItemizedOverlay extends ItemizedOverlay<OverlayItem> {   
		private ArrayList<OverlayItem> mOverlays = new ArrayList<OverlayItem>();
		Context mContext;    
		public HelloItemizedOverlay(Drawable defaultMarker) 
		{   
			super(boundCenterBottom(defaultMarker));
			populate();
		} 
		
		public HelloItemizedOverlay(Drawable defaultMarker, Context context)
		{   
			super(boundCenterBottom(defaultMarker));
			mContext = context;
			populate();
		}  
		
		public void addItem(GeoPoint p, String title, String snippet)
		{
			OverlayItem newItem = new OverlayItem(p, title, snippet);
			mOverlays.add(newItem);   
			populate();
		}
		
		@Override  protected OverlayItem createItem(int i)
		{    
			return mOverlays.get(i); 
		}  
		
		@Override     
		public void draw(Canvas canvas, MapView mapView, boolean shadow) 
		{        
			super.draw(canvas, mapView, shadow);
		}
		
		@Override  
		public int size() 
		{    
			return mOverlays.size();  
		}  
	}
}